package com.hzdl.car.controller;

import com.github.pagehelper.PageInfo;
import com.hzdl.car.bean.Car;
import com.hzdl.car.bean.Customer;
import com.hzdl.car.service.CarService;
import com.hzdl.car.util.HzdlResultJson;
import com.hzdl.car.util.ResultObj;
import com.hzdl.car.vo.CarVo;
import com.hzdl.car.vo.CustomerVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("car")
public class CarController {
    @Resource
    private CarService carService;
    @RequestMapping("findCar")
    public HzdlResultJson findCar(CarVo carVo){
        PageInfo<Car> pageInfo=carService.findCar(carVo);
        return HzdlResultJson.ok(pageInfo.getTotal(),pageInfo.getList());
    }
    @RequestMapping("delCar")
    public ResultObj delCar(CarVo carVo){
        try {
            carService.delCar(carVo);
            return ResultObj.DELETE_SUCCESS;

        }catch (Exception e){
            return  ResultObj.DELETE_ERROR;
        }
    }
    @RequestMapping("carDelChk")
    public ResultObj carDelChk(@RequestParam(value = "ids[]")String[] ids){
        try {
            carService.carDelChk(ids);
            return ResultObj.DELETE_SUCCESS;
        }catch (Exception e){
            return ResultObj.DELETE_ERROR;
        }
    }
    @RequestMapping("uploadImg")
    public HzdlResultJson uploadImg(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request){
        try {
            //获取文件名称
            String fileName=file.getOriginalFilename();

            String path=request.getServletContext().getRealPath("images");
            File file1=new File(path,fileName);
            if(!file1.getParentFile().exists()){
                file1.getParentFile().mkdirs();
            }
            file.transferTo(file1);
            Map<String,Object> map=new HashMap<>();
            map.put("src","/images/"+fileName);
            return HzdlResultJson.ok(map);
        }catch (Exception e){
            return HzdlResultJson.error(2,e.getMessage());
        }
    }
    @RequestMapping("addCar")
    public ResultObj addCar(CarVo carVo){
        try {

            carService.addCar(carVo);
            return ResultObj.ADD_SUCCESS;
        }catch (Exception e){
            return ResultObj.ADD_ERROR;
        }
    }
    @RequestMapping("updateCar")
    public  ResultObj updateCar(CarVo carVo){
        try {
            carService.updateCar(carVo);
            return ResultObj.UPDATE_SUCCESS;
        }catch (Exception e){
            return ResultObj.UPDATE_ERROR;
        }
    }
}
